<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/4
 * Time: 16:18
 */

namespace App\Services;
use App\Lib\Game;
use App\Lib\Option;
use App\Lib\Redis;
use App\Model\Room;
use App\Model\RoomTicket;
use App\Model\RoomTicketJournal;

class RoomService extends BaseService
{

    public function createRoom($arrData){
        $timestamp = time();
        $result = array();
        $return = array();
        $data 			= $arrData['data'];
        $operation 		= $arrData['operation'];
        $account_id 	= $arrData['account_id'];

        if(!isset($data['data_key']) || trim($data['data_key']) == Option::EMPTY_STRING) {
            $this->logger->log("function(createRoom):lack of data_key"." in file".__FILE__." on Line ".__LINE__, "error");
            return $this->_missingPrameterArr($operation,"data_key");
        }

        //庄家类型
        if(isset($data['banker_mode']) && in_array($data['banker_mode'], [Game::BankerMode_FreeGrab,Game::BankerMode_SeenGrab,Game::BankerMode_TenGrab,Game::BankerMode_NoBanker,Game::BankerMode_FixedBanker])) {
            $LimitTime_GrabBetting = Game::LimitTime_GrabBetting[$data['banker_mode']];
        }else{
            $this->logger->log( "function(createRoom):用户".$account_id." banker_mode error："." in file".__FILE__." on Line ".__LINE__,'error');
            return $this->_missingPrameterArr($operation,"banker_mode");
        }

        //筹码大小类型
        if(!isset($data['betting_type']) || !key_exists($data['betting_type'], Game::Rule_BettingType)){
            $this->logger->log("function(createRoom):用户".$account_id." bet_type error：".__FILE__." on Line ".__LINE__, 'error');
            return $this->_missingPrameterArr($operation,"bet_type");
        }

        //人数类型
        if (!isset($data['max_count_type']) || !in_array($data['max_count_type'],  Game::Player_MaxCount)){
            $this->logger->log( "function(createRoom):用户".$account_id." max_count_type error："." in file".__FILE__." on Line ".__LINE__, 'error');
            return $this->_missingPrameterArr($operation,"max_count_type");
        }
        //局数
        if(!isset($data['ticket_type']) || !in_array($data['ticket_type'], Game::Game_NumberEach)){
            $this->logMessage('error', "function(createRoom):用户".$account_id." ticket_type error：".__FILE__.__LINE__);
            return $this->_missingPrameterArr($operation,"ticket_type");
        }

        //默认底分
        if (isset($data['score_type']) && key_exists($data['score_type'])){
            $Rule_ScoreType = Game::Rule_ScoreType[$data['score_type']];
        } else {
            $this->logger->log( "function(createRoom):用户".$account_id." score_type error："." in file".__FILE__." on Line ".__LINE__, 'error');
            return $this->_missingPrameterArr($operation,"score_type");
        }

        //牌型倍率规则
        if (isset($data['rule_type']) && key_exists($data['rule_type'])){
            $Rule_Card_Multiple = Game::Rule_Card_Multiple[$data['rule_type']];
        } else {
            $this->logger->log( "function(createRoom):用户".$account_id." rule_type error："." in file".__FILE__." on Line ".__LINE__, 'error');
            return $this->_missingPrameterArr($operation,"rule_type");
        }


        //我的房卡
        $my_ticket_count = (new RoomTicket())->getTickInfoByAccountID($account_id);
        $spend_ticket_count = Game::Rule_TicketCount[$data['max_count_type']][$data['ticket_type']];
        if($my_ticket_count < $spend_ticket_count){
            $this->logger->log("($account_id) 房卡不足");
            $result['alert_type'] = 1;	//1房卡不足
            return $this->_notAllowArr($operation, $result, "房卡不足");
        }
        $roomModel = new Room();
        if (!$roomInfo = $roomModel->getRoomInfoByDataKey($data['data_key'])){
            $roomInfo['create_time'] = $timestamp ;
            $roomInfo['create_appid'] = $account_id;
            $roomInfo['update_time'] = $timestamp;
            $roomInfo['update_appid'] = $account_id;
            $roomInfo['is_delete'] = Option::IS_FALSE;
            $roomInfo['data_key'] = $data['data_key'];
            $roomInfo['account_id'] = $account_id;
            $roomInfo['is_close'] = Option::IS_FALSE;
            $roomInfo['max_count'] = $data['max_count_type'];
            $roomInfo['max_times'] = Game::Rule_BettingType[$data['betting_type']];

            $roomInfo['room_id'] = $roomModel->insert($roomInfo, false, true);
            if (!$roomInfo['room_id']){
                $this->logger->log( "function(createRoom):用户".$account_id." 创建房间失败："." in file".__FILE__." on Line ".__LINE__, 'error');
                return array("result"=>"-1","operation"=>$operation,"data"=>$result,"result_message"=>"创建房间失败");
            }

            $roomInfo['room_number'] = 100000 + $roomInfo['room_id'] * 10 + mt_rand(1,9);
            $roomModel->update(['room_number'=>$roomInfo['room_number']], ["room_id"=>$roomInfo['room_id']]);
            $this->balanceTicket($roomInfo['room_id'], $account_id, $spend_ticket_count);
        }
        $replyArr = array("[roomid]"=>$roomInfo['room_id']);
        $Room_Key = strtr(Redis::Room_Key, $replyArr);
        $r_mkv[Redis::Room_Field_Number] = $roomInfo['room_number'];	//房间号
        $r_mkv[Redis::Room_Field_GameRound] = 1;			//游戏轮数
        $r_mkv[Redis::Room_Field_GameNum] = 0;			//游戏局数
        $r_mkv[Redis::Room_Field_MaxCount] = $data['max_count_type'];			//游戏人数
        $r_mkv[Redis::Room_Field_Status] = Game::RoomStatus_Waiting;				//房间状态，1等待、2进行中、3关闭
        $r_mkv[Redis::Room_Field_DefaultScore] = $Rule_ScoreType;		//开局默认分数
        $r_mkv[Redis::Room_Field_ActiveUser] = -1;		//当前操作用户
        $r_mkv[Redis::Room_Field_ActiveTimer] = -1;		//当前生效timer
        $r_mkv[Redis::Room_Field_BaseScore] = $Rule_ScoreType;
        $r_mkv[Redis::Room_Field_TotalNum] = Game::Game_NumberEach;		//每轮总局数
        $r_mkv[Redis::Room_Field_TicketCount] = Game::Rule_TicketCount[$data['max_count_type']][$data['ticket_type']];		//每轮消耗房卡数量
        $r_mkv[Redis::Room_Field_Creator] = $account_id;		//创建用户
        $r_mkv[Redis::Room_Field_Scoreboard] = "";		//积分榜
        $r_mkv[Redis::Room_Field_Paytype] = Game::PaymentType_Mode;		//1AA,2房主扣卡

        $r_mkv[Redis::Room_Field_ActiveUser] = -1;		//当前操作用户
        $r_mkv[Redis::Room_Field_ActiveTimer] = -1;		//当前生效timer
        $r_mkv[Redis::Room_Field_ReadyTime] = -1;		//房间倒计时

        $r_mkv[Redis::Room_Field_StartTime] = -1;		//开局时间

        $r_mkv[Redis::Room_Field_BetType]   = $data['betting_type'];      //筹码类型
        $r_mkv[Redis::Room_Field_RuleType]  = $data['rule_type'];	    //规则类型
        $r_mkv[Redis::Room_Field_Multiple]  = $Rule_Card_Multiple;

        $r_mkv[Redis::Room_Field_CardJoker] = isset($data['is_laizi']) && $data['is_laizi'] == 1 ? 1: 0;// 写入redis

        $r_mkv[Redis::Room_Field_BankerMode] = $data['banker_mode'];		//庄家类型
//        $r_mkv[Redis::Room_Field_BankerScoreType] = $banker_scoreType;	    //上庄分数类型
//        $r_mkv[Redis::Room_Field_BankerScore] = $banker_score;	//上庄分数
        $r_mkv[Redis::Room_Field_LT_Ready] = Game::LimitTime_Ready;
        $r_mkv[Redis::Room_Field_LT_Grab] = $LimitTime_GrabBetting["Grab"];
        $r_mkv[Redis::Room_Field_LT_Bet]  = $LimitTime_GrabBetting["Betting"];
        $r_mkv[Redis::Room_Field_LT_Show] = Game::LimitTime_Show;
//        $redisPool = PoolManager::getInstance()->getPool('App\Utility\RedisPool');
        return "123123";
    }

    /**
     *
     * 扣除房卡或退还房卡
     * @param $room_id
     * @param $account_id
     * @param $spend_ticket_count
     * @return int|string
     */
    protected function balanceTicket($room_id, $account_id, $spend_ticket_count){
        $timestamp = time();
        $roomTicketModel = new RoomTicket();
        $ticket_count = (new RoomTicket())->getTicketCountByAccountID($account_id);
        $balance = $ticket_count - $spend_ticket_count;
        $roomTicketModel->update(["ticket_count"=>$ticket_count - $spend_ticket_count], ["account_id"=>$account_id]);


        //添加到流水账
        $journal_array['create_time'] = $timestamp;
        $journal_array['create_appid'] = "aid_".$account_id;
        $journal_array['update_time'] = $timestamp;
        $journal_array['update_appid'] = "aid_".$account_id;
        $journal_array['is_delete'] = Option::IS_FALSE;
        $journal_array['account_id'] = $account_id;
        $journal_array['object_id'] = $room_id;
        $journal_array['object_type'] = Option::OBJECT_TYPE_CREATEROOM;  //类型

        $journal_array['extra'] = "";
        $journal_array['abstract'] = "";		//摘要

        if($spend_ticket_count > 0) {
            $journal_array['disburse'] = abs($spend_ticket_count);
        } else {
            $journal_array['income'] = abs($spend_ticket_count);
        }
        $journal_array['balance'] = $balance - $spend_ticket_count;
        if($journal_array['balance'] < 0){
            $journal_array['balance'] = 0;
        }
        return (new RoomTicketJournal())->insert($journal_array);
    }

}